package com.stox.client.ui.javafx.chartingy.widget;

import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.control.SplitPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Line;

import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;

public class Crosshair extends Group implements EventHandler<MouseEvent> {

	private final ChartingView chartingView;
	private final Line vertical = new Line();
	private final Line horizontal = new Line();

	public Crosshair(final ChartingView chartingView) {
		this.chartingView = chartingView;
		setManaged(false);
		setMouseTransparent(true);
		setVisible(false);
		UI.style(this, CSS.crosshair);
		SplitPane pane = chartingView.getSplitPane();
		pane.addEventFilter(MouseEvent.ANY, this);

		vertical.endXProperty().bindBidirectional(vertical.startXProperty());
		vertical.startYProperty().bind(pane.layoutYProperty());
		vertical.endYProperty().bind(pane.layoutYProperty().add(pane.heightProperty()));
		horizontal.endYProperty().bindBidirectional(horizontal.startYProperty());
		horizontal.startXProperty().bind(pane.layoutXProperty());
		horizontal.endXProperty().bind(pane.widthProperty());
		getChildren().addAll(vertical, horizontal);
	}

	@Override
	public void handle(final MouseEvent event) {
		if (MouseEvent.MOUSE_ENTERED.equals(event.getEventType())) {
			setVisible(true);
		} else if (MouseEvent.MOUSE_EXITED.equals(event.getEventType())) {
			setVisible(false);
		} else if (MouseEvent.MOUSE_MOVED.equals(event.getEventType()) || MouseEvent.MOUSE_DRAGGED.equals(event.getEventType())) {
			setVisible(true);
			Point2D point = chartingView.getCenter().sceneToLocal(event.getSceneX(), event.getSceneY());
			vertical.setStartX(point.getX());
			horizontal.setStartY(point.getY());
			setVisible(null != chartingView.resolveChart(event.getSceneX(), event.getSceneY()));
		}
	}
}
